package com.poxz.common.exception;

import com.poxz.common.response.Result;
import com.poxz.common.response.ResultCode;
import com.poxz.common.response.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *
 * @author poxz
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 处理业务异常
     *
     * @param e 异常对象
     * @return Result
     */
    @ExceptionHandler(BusinessException.class)
    public Result<String> handleBusinessException(BusinessException e) {
        String message = e.getMessage();

        if (message == null || message.equals(e.getResultCode().getMessage())) {
            message = e.getResultCode().getMessage();
        }
        log.error("业务异常: {}", message);
        return ResultUtils.fail(e.getResultCode().getCode(), message);
    }

    /**
     * 处理参数校验异常
     *
     * @param e 异常对象
     * @return Result
     */
    @ExceptionHandler(Exception.class)
    public Result<String> handleException(Exception e) {
        log.error("系统异常", e);
        return ResultUtils.fail(ResultCode.FAIL);
    }
}

